<?php
/**
* 微信公众号
*/
class mc_weixin_user extends ms_base
{
	private $role_obj = null;
	private $info_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token={ACCESS_TOKEN}&openid={OPENID}&lang={zh_CN}';

	function __construct($role)
	{

		parent::__construct();
		$this->role_obj = $role;
		//$this->role_obj->getAccessToken(); //获取权限令牌
	}

	function info($openid, $lang='zh_CN')
	{
		static $force = false; //是否强制刷新access_token
		$access_token = $this->role_obj->getAccessToken($force);
		if(!$access_token) {
			return $this->add_error('未获取微信授权令牌（Access_Token）');
		}		
		$url = str_replace(array('{ACCESS_TOKEN}','{OPENID}','{zh_CN}'), 
			array($access_token,$openid,$lang), $this->info_url);
		$result = $this->http_get($url);
		if(!$result) return false;
		$json = json_decode($result);
		if($json->errcode) {
			if(in_array($json->errcode, array('41001','42001','42002','42007')) && !$force) {
				//access_token问题
				$force = true; //强制刷新access_token
				return $this->info($openid, $lang);
			}
			$force = false;
			return $this->add_error($json->errmsg.'(errcode:'.$json->errcode.')');
		}
		return $json;
	}

	private function http_post($url, $data) {
		if(!function_exists('curl_exec')) {
			return $this->add_error('服务器PHP未开启 curl 扩展模块');
		}
        $ch = curl_init ($url);
        curl_setopt ($ch, CURLOPT_POST, 1);
        curl_setopt ($ch, CURLOPT_HEADER, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST,  false);
        curl_setopt ($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        //错误记录
        $error = curl_error($ch);
        if($error) {
            $message = "微信自定义菜单提交失败\t$error\n$url";
            log_write('weixin', $message);
            return $this->add_error('提交失败。');
        }
        if(DEBUG) log_write('weixin_debug', $url."\n".$result);
        curl_close($ch);
        return $result;
	}

	private function http_get($url) {
		if(!function_exists('curl_exec')) {
			return $this->add_error('服务器PHP未开启 curl 扩展模块');
		}
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        $result =  curl_exec($ch);
        //错误记录
        $error = curl_error($ch);
        if($error) {
            $message = "微信自定义菜单提交失败\t$error\n$url";
            log_write('weixin', $message);
            return $this->add_error('提交失败。');
        }
        if(DEBUG) log_write('weixin_debug', $url."\n".$result);
        curl_close($ch);
        return $result;
	}
}
/** end **/